/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.book.web;

import com.alibaba.druid.support.json.JSONUtils;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.utils.HttpClientUtil;
import com.thinkgem.jeesite.common.utils.MarcUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.book.entity.BkBookinfo;
import com.thinkgem.jeesite.modules.book.entity.BkBooks;
import com.thinkgem.jeesite.modules.book.entity.BkBookstore;
import com.thinkgem.jeesite.modules.book.entity.BkType;
import com.thinkgem.jeesite.modules.book.service.BookMgrService;
import com.thinkgem.jeesite.modules.book.service.BookStoreService;
import com.thinkgem.jeesite.modules.book.service.BookTypeService;
import com.thinkgem.jeesite.modules.book.service.BooksService;
import com.thinkgem.jeesite.modules.borrow.service.BorrowService;
import com.thinkgem.jeesite.modules.sys.utils.BkTypeUtils;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 流程个人任务相关Controller
 *
 * @author ThinkGem
 * @version 2013-11-03
 */
@Controller
@RequestMapping(value = "${adminPath}/book/manage")
public class BookMgrController extends BaseController{

    public static final String DOUBAN_BOOK_API = "https://api.douban.com/v2/book/isbn/";

    @Autowired
    private BookStoreService bookStoreService;
    @Autowired
    private BookMgrService bookMgrService;
    @Autowired
    private BookTypeService bookTypeService;
    @Autowired
    private BorrowService borrowService;
    @Autowired
    private BooksService booksService;


    @ModelAttribute
    public BkBookinfo get(@RequestParam(required = false) String id){
        if(StringUtils.isNotBlank(id)){
            return bookMgrService.get(id);
        }
        else{
            return new BkBookinfo();
        }
    }


    @RequiresPermissions("book:manage:view")
    @RequestMapping(value = {"list", ""})
    public String list(BkBookinfo bkBookinfo, HttpServletRequest request, HttpServletResponse response, Model model){
        Page<BkBookinfo> page = bookMgrService.findPage(new Page<BkBookinfo>(request, response), bkBookinfo);
        List<BkBookinfo> list = page.getList();
        for(BkBookinfo bookinfo:list){
            BkType bkType = BkTypeUtils.getType(bookinfo.getClasscode());
            bookinfo.setBkType(bkType);
        }
        model.addAttribute("page", page);
        return "modules/book/bookInfoList";
    }

    @RequiresPermissions("book:manage:view")
    @RequestMapping(value = "form")
    public String form(Model model){
        return "modules/book/bookMgrForm";
    }

    @RequestMapping(value = "analyse")
    public String analyse(HttpServletRequest request, MultipartFile mfile){
        List<BkBookinfo> cnmarcList = null;
        try{
            if(mfile.getOriginalFilename().endsWith("iso")){
                CommonsMultipartFile cf = (CommonsMultipartFile)mfile;
                DiskFileItem fi = (DiskFileItem)cf.getFileItem();
                InputStream inputStream = fi.getInputStream();
                cnmarcList = MarcUtils.readMarc(inputStream, "GB2312");
            }
            else{
                ImportExcel ei = new ImportExcel(mfile, 0, 0);
                cnmarcList = ei.getDataList(BkBookinfo.class);
                for(int i = cnmarcList.size()-1; i >= 0; i--){
                    BkBookinfo tem = cnmarcList.get(i);
                    if(null == tem){
                        cnmarcList.remove(i);
                    }
                    else{
                        if(StringUtils.isEmpty(tem.getBookname())){
                            cnmarcList.remove(tem);
                        }
                        else{
                            tem.setIsbn(tem.getIsbn().replaceAll("-",""));
                        }
                    }

                }
            }
        }
        catch(Exception e){
            logger.error("解析marc数据出错", e);
        }
        request.getSession().setAttribute("cnmarcList", cnmarcList);
        return "modules/book/bookMgrForm";
    }

    @RequiresPermissions("book:manage:save")
    @RequestMapping(value = "save")
    @ResponseBody
    public Result save(HttpServletRequest request){

        List<BkBookinfo> cnmarcList = (List)request.getSession().getAttribute("cnmarcList");
        int amount = 0;
        for(BkBookinfo bkBookinfo : cnmarcList){
            try{
                String id = bkBookinfo.getId();
                if(!isDigit(id) || id.length() >= 12){
                    bkBookinfo.setId("0");
                }

                bookMgrService.insert(bkBookinfo);

                String booksName = bkBookinfo.getBooks();
                if(StringUtils.isNotEmpty(booksName)){
                   boolean hasBooks = booksService.hasBooks(booksName);
                    if(!hasBooks){
                        booksService.save(new BkBooks(booksName, "0"));
                    }
                }
                amount++;
            }
            catch(Exception e){
                logger.error("导入marc数据出错", e);
                /*return new Result(Result.FAILURE, "保存数据存在失败！", null);*/
            }
        }

        request.getSession().setAttribute("cnmarcList", null);
        return new Result("marc数据一共" + cnmarcList.size() + "条，成功导入" + amount + "条！");
    }


    @RequiresPermissions("book:manage:view")
    @RequestMapping("listData")
    public String listData(BkBookinfo bkBookinfo, HttpServletRequest request, HttpServletResponse response, Model model){
        // 查询馆藏数量>0的书籍
        Page<BkBookinfo> page = bookMgrService.findBorrowPage(new Page<>(request, response), bkBookinfo);
        model.addAttribute("page", page);
        return "modules/book/bookInfoListData";
    }


    /**
     * 获取读者信息返回json串
     */
    @ResponseBody
    @RequestMapping(value = "getBookInfoByISBN")
    public String getBookInfoByISBN(@RequestParam(required=false) String bookISBN){
        String ret = null;
        if(StringUtils.isNotBlank(bookISBN)){
            BkBookinfo bookinfo = bookMgrService.getByIsbn(bookISBN);
            JsonMapper jsonMapper =new JsonMapper();
            ret = jsonMapper.toJson(bookinfo);
        }
        return ret;
    }

    /**
     * 获取图书信息返回json串
     */
    @ResponseBody
    @RequestMapping(value = "getBookInfoById")
    public BkBookinfo getBookInfoById(String bkId){
        return bookMgrService.get(bkId);
    }


    /**
     * 获取图书信息返回json串
     */
    @ResponseBody
    @RequestMapping(value = "getBookInfoBybandid")
    public String getBookInfoBybandid(@RequestParam(required=false) String banid){
        String ret = null;
        if(StringUtils.isNotBlank(banid)){
            //判断该banid是否已经被借出，如果借出直接返回“flag:1”
            int isCount = borrowService.findExistBook(banid);
            JsonMapper jsonMapper =new JsonMapper();
            if(isCount>0){
                String tempStr = "{\"isCount\":\""+isCount+"\"}";
                ret = tempStr;
            } else {
                BkBookinfo bookinfo = bookMgrService.getBybanid(banid);

                ret = jsonMapper.toJson(bookinfo);
            }
        }
        return ret;
    }

    @RequestMapping(value = "getByIsbn")
    @ResponseBody
    public List<BkBookinfo> getByIsbn(String isbn){
        return bookMgrService.getBookInfosByIsbn(isbn);
    }

    @RequestMapping(value = "selectBook")
    public String selectBook(String isbn, Model model){
        List<BkBookinfo> bookInfos = getByIsbn(isbn);
        model.addAttribute("bookInfos", bookInfos);
        return "modules/book/pop/selectBook";
    }


    @RequiresPermissions("book:manage:view")
    @RequestMapping("get")
    public String getInfo(String bkId, String isbn, Model model){
        BkBookinfo bkBookinfo;
        if(StringUtils.isNotBlank(bkId)){
            bkBookinfo = bookMgrService.get(bkId);
        }
        else{
            bkBookinfo = new BkBookinfo();
            if(StringUtils.isNotEmpty(isbn)){
                bkBookinfo.setIsbn(isbn);
            }
        }
        model.addAttribute("bkBookinfo", bkBookinfo);
        return "modules/book/bookInfoEdit";
    }

    /**
     *  继续新增
     *
     * @param request
     * @return
     */
    @RequiresPermissions("book:manage:save")
    @RequestMapping("continue")
    public String continueInsert(RedirectAttributes redirectAttributes, HttpServletRequest request, Model model){
        BkBookinfo bkBookinfo = (BkBookinfo)request.getAttribute("bkBookinfo");
        bkBookinfo.setId("");
        model.addAttribute("bkBookinfo", bkBookinfo);
        request.setAttribute("message", request.getAttribute("message"));
        return "modules/book/bookInfoEdit";
    }

    @RequestMapping("show")
    public String bookShow(String bkId, Model model){
        BkBookinfo bkBookinfo = bookMgrService.get(bkId);
        model.addAttribute("bkBookinfo", bkBookinfo);
        return "modules/book/bookInfoShow";
    }

    @RequiresPermissions("book:manage:save")
    @RequestMapping("edit")
    public String edit(BkBookinfo bkBookinfo, boolean pop, RedirectAttributes redirectAttributes, HttpServletRequest request){
        String message = "保存图书字段成功";
        if(StringUtils.isEmpty(bkBookinfo.getId())){
            try{
                bkBookinfo.setId("0");
                BkType bkType = bookTypeService.get(bkBookinfo.getClasscode());
                if(null != bkType){
                    bkBookinfo.setClasscode(bkType.getTypName());
                }
                bookMgrService.saveBookInfo(bkBookinfo);
                addMessage(redirectAttributes, message);
                request.setAttribute("message", message);
            }
            catch(Exception e){
                message = "保存图书字段失败，请重新提交";
                addMessage(redirectAttributes, message);
                request.setAttribute("message", message);
                logger.error("----------- BookMgrController.edit()", e);
            }
            if(pop){
                return "redirect:" + adminPath + "/book/manage/get?bkId=" + bkBookinfo.getId();
            }
            else{
                request.setAttribute("bkBookinfo", bkBookinfo);
                return "forward:" + adminPath + "/book/manage/continue";
            }
        }
        else{
            bookMgrService.saveBookInfo(bkBookinfo);
            addMessage(redirectAttributes, "保存图书字段成功");
            if(pop){
                return "redirect:" + adminPath + "/book/manage/get?bkId=" + bkBookinfo.getId();
            }
            else{
                return "redirect:" + adminPath + "/book/manage/?repage&id=" + bkBookinfo.getId();
            }
        }
    }

    @RequiresPermissions("book:manage:delete")
    @RequestMapping("delete")
    @ResponseBody
    public Result delete(String bkId){
        List<BkBookstore> bkBookstores= bookStoreService.getStoresByBkId(bkId);
        if(null == bkBookstores || bkBookstores.isEmpty()){
            BkBookinfo bkBookinfo = new BkBookinfo();
            bkBookinfo.setId(bkId);
            bookMgrService.delete(bkBookinfo);
            return new Result(Result.SUCCESS, "删除书籍信息成功！", null);
        }else{
            return new Result(Result.SUCCESS, "存在库存不能删除！", null);
        }
    }

    @RequestMapping("searchBooksFromApi")
    @ResponseBody
    public Result searchBooksFromApi(String isbn){
        String book_info = HttpClientUtil.post(DOUBAN_BOOK_API + isbn,"", 6000);
        if(StringUtils.isBlank(book_info)){
            return new Result(Result.FAILURE, "", null);
        }
        else{
            Map book = (Map)JSONUtils.parse(book_info);
            BkBookinfo bookInfo = new BkBookinfo(book);
            return new Result(Result.SUCCESS, "", bookInfo);
        }
    }

    public boolean isDigit(String str){
        if(null == str || str.length() == 0){
            return false;
        }

        for(int i = str.length(); --i >= 0; ){
            int c = str.charAt(i);
            if(c < 48 || c > 57){
                return false;
            }
        }

        return true;
    }

    /**
     * 下载模板
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "图书信息导入模板.xlsx";
            new ExportExcel("",BkBookinfo.class, 2).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
        }
        return "redirect:" + adminPath + "/book/manage/form";
    }

    /**
     * 导出所有书目信息
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "exportAll")
    public String exportAll(HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "所有书目信息.xlsx";
            Page<BkBookinfo> page = bookMgrService.findPage(new Page<BkBookinfo>(request, response, -1), new BkBookinfo());

            new ExportExcel("",BkBookinfo.class, 2).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
        }
        return "redirect:" + adminPath + "/book/manage/list";
    }
}
